package com.raising.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.raising.framework.entity.ResultVo;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 通过 request 获取数据
 * @author GaoYuan
 * @date 2018/11/20 上午10:55
 */
public class RequestUtils {

    /**
     * 获得用户远程地址
     */
    public static String getRemoteAddr(HttpServletRequest request) {
        String remoteAddr = request.getHeader("X-Real-IP");
        if (remoteAddr != null && !"".equals(remoteAddr)) {
            remoteAddr = request.getHeader("X-Forwarded-For");
        } else if (remoteAddr != null && !"".equals(remoteAddr)) {
            remoteAddr = request.getHeader("Proxy-Client-IP");
        } else if (remoteAddr != null && !"".equals(remoteAddr)) {
            remoteAddr = request.getHeader("WL-Proxy-Client-IP");
        }
        return remoteAddr != null ? remoteAddr : request.getRemoteAddr();
    }

    /**
     * 是否是ajax请求
     * @author GaoYuan
     * @date 2018/11/20 下午2:14
     */
    public static boolean isAjax(HttpServletRequest request){
        return "XMLHttpRequest".equalsIgnoreCase(request.getHeader("X-Requested-With"));
    }

    /**
     * ajax 返回方法
     * @author GaoYuan
     * @date 2018/11/20 下午2:16
     */
    public static void ajaxResponse(HttpServletResponse response, Object result){
        response.setCharacterEncoding("UTF-8");
        try(PrintWriter out = response.getWriter()) {
            JSONObject jsonObject = (JSONObject) JSON.toJSON(result);
            out.println(jsonObject);
            out.flush();
            out.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
